package com.huamoxi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huamoxi.entity.User;
import com.huamoxi.mapper.RoleMapper;
import com.huamoxi.mapper.UserMapper;
import com.huamoxi.response.UserInfoResponse;
import com.huamoxi.result.Result;
import com.huamoxi.service.UserService;
import com.huamoxi.utils.JwtUtil;
import com.huamoxi.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Result register(User user) {
        try {
            User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, user.getAccount()).eq(User::getSystemId, user.getSystemId()));
            if (one != null) {
                return ResultUtil.fail("该用户已注册");
            }

            user.setPassword(passwordEncoder.encode(user.getPassword()));

            if (save(user)) {
                return ResultUtil.success("注册成功");
            } else {
                return ResultUtil.fail("注册失败");
            }
        } catch (Exception e) {
            return ResultUtil.fail("注册失败" + e.getMessage());
        }
    }

    @Override
    public Result<UserInfoResponse> getUserInfo(String token) {
        UserInfoResponse response = new UserInfoResponse();
        Claims claims = jwtUtil.verifyToken(token);
        Integer systemId = Integer.parseInt(claims.get("systemId").toString());
        User usr = userMapper.selectOne(
                Wrappers.<User>lambdaQuery()
                        .eq(User::getSystemId, systemId)
                        .eq(User::getAccount, claims.getSubject())
        );
        BeanUtil.copyProperties(usr, response);
        // 查询是否为管理员
        Boolean isAdmin = roleMapper.isAdmin(Long.parseLong(claims.get("id").toString()));
        response.setIsAdmin(isAdmin);
        return ResultUtil.success(response);
    }
}
